package com.augurit.gzcgwsp.wfex.bi.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletOutputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.base.action.ExtBaseAction;
import com.augurit.common.base.action.ExtCrudActionSupport;
import com.augurit.common.base.extmodel.BasicCombo;
import com.augurit.common.base.extmodel.inner.ExtMetaColumnNode;
import com.augurit.common.base.extmodel.inner.ExtMetaTableNode;
import com.augurit.common.base.form.Attachment;
import com.augurit.common.base.form.ResultForm;
import com.augurit.common.constant.SystemConstant;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.sysmeta.convert.SysMetaColumnConvertor;
import com.augurit.common.sysmeta.convert.SysMetaTableConvertor;
import com.augurit.common.sysmeta.service.ISysMetaColumnService;
import com.augurit.common.sysmeta.web.form.SysMetaColumnForm;
import com.augurit.common.sysmeta.web.form.SysMetaTableForm;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.ActionUtils;
import com.augurit.common.util.ExtUtils;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.ywcmn.service.IBaseDistrictService;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.service.IWfBusTemplateTypeService;
import com.augurit.wf.bi.service.IWfTemplateAttachmentRefService;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.bi.web.form.WfBusTemplateTypeForm;
import com.augurit.wf.bi.web.form.WfTemplateAttachmentRefForm;

@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "wf-template-print-ref.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/wf/bi/bus-template/edit-print-template.jsp"),
	@Result(name = WfTemplatePrintRefEXAction.EDIT_FORM_PRINT_TEMPLATE, location = "/wf/bi/bus-template/edit-form-and-print-template.jsp")
})
public class WfTemplatePrintRefEXAction extends ExtCrudActionSupport<WfTemplateAttachmentRefForm> {
    private static final Log log=LogFactory.getLog(WfTemplatePrintRefEXAction.class);
	
	private static final String EDIT_FORM_PRINT_TEMPLATE = "edit-form-print-template";	//对应
	
	@Autowired
	private IWfBusTemplateService wfBusTemplateService;
	
	@Autowired
	private IWfTemplateAttachmentRefService wfTemplatePrintRefService;
	
	@Autowired
	private IWfTemplateAttachmentRefServiceEX wfTemplatePrintRefServiceEX;
	
	@Autowired
	private ISysMetaColumnService sysMetaColumnService;
	@Autowired
    private ISysCodeService syscodeService;
	
	@Autowired
	private IYwPrintDocService ywPrintDocService;
	
	@Autowired
	private IBaseDistrictService baseDistrictService;
    @Autowired
	private IWfBusTemplateTypeService wfBusTemplateTypeService;
	//private Page<WfTemplateAttachmentRefForm> page = new Page<WfTemplateAttachmentRefForm>(15);
	//private WfTemplateAttachmentRefForm form;
	
	private Page<WfTemplateAttachmentRefFormEX> page = new Page<WfTemplateAttachmentRefFormEX>(15);
	private WfTemplateAttachmentRefFormEX form;
	
	private Long id;
	private Long[] ids;
	
	private Attachment document; 	//保存ntko文档文件对象
	
	/**
	 * 显示业务流程对应的打印模板列表
	 */
	@Override
	public String list() throws Exception {
		ExtUtils.initPageFromExtGridParam(ExtBaseAction.getRequest(), page);
		//wfTemplatePrintRefServiceEX.search(page, form);
		ExtBaseAction.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 显示模板下的所以红头文件
	 * @return
	 * @throws Exception
	 */
	public String listRedHeadFiles() throws Exception {
//		String regionDistrictStr = omOrgServiceEX.getRegionByUserId(this.getLoginUserId());
		LoginUserForm loginUser = (LoginUserForm)Struts2Utils.getSessionAttribute(WebContextUtils.SES_LOGIN_USER);		
		String allQu = "天河,白云,荔湾,黄埔,萝岗,增城,从化,南沙,海珠,番禺,越秀,花都";//12区
		String bmmc = loginUser.getOrg().getOrgName();//部门名称
		if(StringUtils.isNotBlank(bmmc) && allQu.contains(bmmc.substring(0, 2))){//区的
			//获取区的指定红头
			List<WfTemplateAttachmentRefForm> lists = wfTemplatePrintRefServiceEX.getQuRedHeadFiles(form,loginUser);
			List<BasicCombo> combos = new ArrayList<BasicCombo>();
			if(lists != null && lists.size() > 0){
				for(int i = 0; i < lists.size(); i++){
					WfTemplateAttachmentRefForm printForm = lists.get(i);
					BasicCombo combo = new BasicCombo();
					combo.setLabel(printForm.getFileName());
					combo.setValue(printForm.getId() + "");
					combos.add(combo);
				}
			}
			ExtBaseAction.extRenderListJson(combos, true);		
		}else{//市的
			List<WfTemplateAttachmentRefForm> list=wfTemplatePrintRefServiceEX.listAllRedHeadFiles(form.getTemplateCode());
			List<BasicCombo> combos = new ArrayList<BasicCombo>();
			for(int i = 0; i < list.size(); i++){
				WfTemplateAttachmentRefForm printForm = list.get(i);
				BasicCombo combo = new BasicCombo();
				combo.setLabel(printForm.getFileName());
				combo.setValue(printForm.getId() + "");
				combos.add(combo);
			}
			ExtBaseAction.extRenderListJson(combos, true);		
		}
		return null;
	}
	//***     zhuhx add      **//
	/**
	 * 显示模板下的所以红头文件
	 * @return
	 * @throws Exception
	 */
	public String listZhengWenFiles() throws Exception {
		
		List<WfTemplateAttachmentRefForm> list = wfTemplatePrintRefServiceEX.listAllZhengWenFiles(form.getTemplateCode());
		if(list != null && list.size() > 0){
			List<BasicCombo> combos = new ArrayList<BasicCombo>();
			for(int i = 0; i < list.size(); i++){
				WfTemplateAttachmentRefForm printForm = list.get(i);
				String actname=form.getActivityName();
				String filename= printForm.getFileName();
				if(("jbrsl".equals(actname) &&filename.indexOf("补正材料通知书")!=-1)&& ("jbrsj".equals(actname) &&filename.indexOf("补正材料通知书")!=-1)){
					BasicCombo combo = new BasicCombo();
					combo.setLabel(printForm.getFileName());
					combo.setValue(printForm.getId() + "");
					combos.add(combo);
					break;
				}else if(!"jbrsl".equals(actname) && filename.indexOf("补正材料通知书") == -1 &&("jbrsj".equals(actname) &&filename.indexOf("补正材料通知书")!=-1)){
					BasicCombo combo = new BasicCombo();
					combo.setLabel(printForm.getFileName());
					combo.setValue(printForm.getId() + "");
					combos.add(combo);
				}
			}
			ExtBaseAction.extRenderListJson(combos, true);
		}
		return null;
	}
	public String listAllZhengWenFilesByPriv() throws Exception {
	    String versionStr=getRequest().getParameter("version");
	    Integer version=null;
	    if(StringUtils.isNotBlank(versionStr)){
	        version=Integer.valueOf(versionStr);
	    }
		List<WfTemplateAttachmentRefForm> list = wfTemplatePrintRefServiceEX.listAllZhengWenFilesByPriv(form.getTemplateCode(),form.getActivityName(),version);
		if(list != null && list.size() > 0){
			List<BasicCombo> combos = new ArrayList<BasicCombo>();
			for(int i = 0; i < list.size(); i++){
				WfTemplateAttachmentRefForm printForm = list.get(i);
				String actname=form.getActivityName();
                String filename= printForm.getFileName();
				if("jbrsj".equals(actname)){//经办人办结
				    if(filename.indexOf("补正材料通知书")<=0){//不显示行政许可补正材料通知书
        				BasicCombo combo = new BasicCombo();
        				combo.setLabel(printForm.getFileName());
        				combo.setValue(printForm.getId() + "");
        				combos.add(combo);
				    }
				}else{
				    BasicCombo combo = new BasicCombo();
                    combo.setLabel(printForm.getFileName());
                    combo.setValue(printForm.getId() + "");
                    combos.add(combo);
				}
			}
			ExtBaseAction.extRenderListJson(combos, true);
		}
		return null;
	}
	//***     zhuhx end      **//
	
	/**
	 * 保存上传的打印模板打印模板及对应的表单
	 */
	@Override
	public String save() throws Exception {
		List<Attachment> attachments = this.getAttachmentList();
		
		if(attachments == null || attachments.size() != 1){
			throw new Exception("上传打印模板失败！");
		}
		else {
			//上传附件
			Attachment attachment = attachments.get(0);
			// huyoxo add begin ---------------------------------------
	        // 随机生成文件名后缀
	        String formatDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
	        int random = new Random().nextInt(1000000);
	        String targetFileName = formatDate + random + attachment.getFileFileName().substring(attachment.getFileFileName().indexOf("."));
            // huyoxo add end ---------------------------------------
	        
			this.uploadFile(form.getFilePath(), targetFileName, attachment, false, true, true);
			//this.uploadFile(form.getFilePath(), attachment.getFileFileName(), attachment, false, true, true);
			
			//this.uploadFile(form.getFilePath(), attachment.getFileFileName(), attachment, false, true, true);
			
			// xu add begin ---------------------------------------
			//所属区
			String belongArea = form.getMemo();
			System.out.println(belongArea);
			if(StringUtils.isNotEmpty(belongArea)){
				//获取区名称，如：天河、越秀
				String areaName = belongArea.substring(0, 2);
				System.out.println(areaName);
				Long districtId = baseDistrictService.getBaseDistrictIdByDistrictNameAndDistrictLevel(areaName);
				//把区配置到memo字段里面
				if(districtId != null){
					form.setMemo(districtId.toString());
				}
			}
			// xu add end ---------------------------------------
			
			//保存form
			form.setFileName(attachments.get(0).getFileFileName());
			form.setFileRealName(targetFileName);
			wfTemplatePrintRefServiceEX.save(form);
			renderHtml("{'success':true}");
		}
		return null;
	}
	
	/**
	 * 删除打印模板
	 */
	@Override
	public String delete() throws Exception {
		if(ids != null && ids.length > 0){
			for(Long id:ids){
				wfTemplatePrintRefService.deleteCascade(id);
			}
		}
		ExtBaseAction.extRenderSuccess();
		return null;
	}

	/**
	 * 编辑打印模板及对应的表单
	 * @return
	 * @throws Exception
	 */
	public String editFormAndPrintTemplate() throws Exception {
		 // 秘密等级
        List<SysCodeForm> fileTypeList = syscodeService.getItems("WF_PRINT_TPL_TYPE");
        if(form != null && form.getFileType() != null){
        	for(SysCodeForm code : fileTypeList){
        		if(code.getItemCode().equals(form.getFileType()))
        			form.setFileTypeChineseName(code.getItemName());
        	}
        }
        super.getRequest().setAttribute("fileTypeList", fileTypeList);
        return EDIT_FORM_PRINT_TEMPLATE;
	}
	
	/**
	 * 保存打印模板及对应的表单
	 * @return
	 * @throws Exception
	 */
	public String saveFormAndPrintTemplate() throws Exception {
		ResultForm result = new ResultForm(true);
		boolean success = this.uploadFile(form.getFilePath(), form.getFileName(), document, false, true, true);
		if(success){
			wfTemplatePrintRefService.save(form);
			result.setErrMsg("已成功保存附件！");
		}
		else{
			ActionUtils.setErrMsgOfResult(result, "上传附件内容失败！");
		}
		this.renderJson(result, SystemConstant.ENCODING_GBK);
		return null;
	}
	
	
	 /**
     * 读取证书打印模板文件
     * @return
     * @throws Exception
     */
    public String readPrintZsFile() throws Exception{
        InputStream in = null;
        ServletOutputStream out = null;
        //***  zhuhx add  **/
        String filePathName = getRequest().getParameter("templateFilePath");
        try {
            File file = null;
            log.info("生成打印模版文件路径----------->"+filePathName);
            filePathName =getRequest().getSession().getServletContext().getRealPath("/") +  filePathName;
            file = new File(filePathName);
            if(!file.exists()){
                log.error("证书的模版文件不存在");
            }
            
            //重置response
            ExtBaseAction.getResponse().reset();
            ExtBaseAction.getResponse().setContentType("application/octet-stream");
            ExtBaseAction.getResponse().setHeader("Content-Disposition","attachment; filename=" + filePathName);
            in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
            out = ExtBaseAction.getResponse().getOutputStream();
            byte[] buffer = new byte[BUFFER_SIZE];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if(in != null) {
                    in.close();
                }
                if(out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return null;
    }
    
	
	
	
	/**
	 * 读取打印模板文件
	 * @return
	 * @throws Exception
	 */
	public String readPrintTemplateFile() throws Exception{
		InputStream in = null;
    	ServletOutputStream out = null;
    	
    	//***  zhuhx add  **/
    	String filePathName = "";
    	if(form.getYwId() != null && form.getYwId() > 0){
    		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getYwId());
        	//经营许可的管道和企业资质考核表始终用模版
    		if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0 &&
        			!"gdbaseInfoFile".equals(form.getFileCode()) && !"gdbaseInfoFile".equals(form.getFileCode())){
    			YwPrintDocForm ypdf = ywPrintDocFormList.get(0);
    			filePathName = ypdf.getPath();
    		}else{
    			filePathName = wfTemplatePrintRefServiceEX.getPrintTemplateRelativePath(form.getTemplateCode(), form.getFileCode()) ;
    		}
    	}else{
    		filePathName = wfTemplatePrintRefServiceEX.getPrintTemplateRelativePath(form.getTemplateCode(), form.getFileCode()) ;
    	}
    	Long templateId=form.getTemplateId();
    	if(templateId!=null){
    	WfBusTemplateForm template=wfBusTemplateService.get(templateId);
    	Long tempTypeId=template.getTemplateTypeId();
    	WfBusTemplateTypeForm type=wfBusTemplateTypeService.get(tempTypeId);
    	//排放消纳的收件通知书用另外的模版,因为每个类型的收件材料
    	if(("余泥".equals(type.getTemplateTypeName()) ||"建筑废弃物处置证".equals(type.getTemplateTypeName()) ) &&
    			template.getTemplateName().indexOf("运输")<=0 && ("sjtzs".equals(form.getFileCode()) || "qusjtzs".equals(form.getFileCode()))){
    			Map<String,String> map=ywPrintDocService.getMapByTemplate(template.getTemplateCode(),
    					String.valueOf(form.getYwId()));
    			String gclb=map.get("gclb");//工程类别
    			if("1".equals(gclb)){//房屋建筑工程类
    				filePathName="/Templates/sjtzspfxn1.doc";
    				if("qusjtzs".equals(form.getFileCode())){
    					filePathName="/Templates/qusjtzspfxn1.doc";
    				}
    			}else if("2".equals(gclb)){// 房屋拆卸类 
    				filePathName="/Templates/sjtzspfxn2.doc";
    				if("qusjtzs".equals(form.getFileCode())){
    					filePathName="/Templates/qusjtzspfxn2.doc";
    				}
    			}else if("3".equals(gclb)){//平整场地（含劈山）工程类
    				filePathName="/Templates/sjtzspfxn3.doc";
    				if("qusjtzs".equals(form.getFileCode())){
    					filePathName="/Templates/qusjtzspfxn3.doc";
    				}
    			}else if("4".equals(gclb)){//市政建设工程（包括道路、桥梁、管线、地铁工程）类
    				filePathName="/Templates/sjtzspfxn4.doc";
    				if("qusjtzs".equals(form.getFileCode())){
    					filePathName="/Templates/qusjtzspfxn4.doc";
    				}
    			}else if("5".equals(gclb)){//房屋室内外装修类
    				filePathName="/Templates/sjtzspfxn5.doc";
    				if("qusjtzs".equals(form.getFileCode())){
    					filePathName="/Templates/qusjtzspfxn5.doc";
    				}
    			}else if("6".equals(gclb)){//市政设施维护维修类
    				filePathName="/Templates/sjtzspfxn6.doc";
    				if("qusjtzs".equals(form.getFileCode())){
    					filePathName="/Templates/qusjtzspfxn6.doc";
    				}
    			}else if("7".equals(gclb)){//受纳建筑废弃物类
    				filePathName="/Templates/sjtzspfxn7.doc";
    				if("qusjtzs".equals(form.getFileCode())){
    					filePathName="/Templates/qusjtzspfxn7.doc";
    				}
    			}else if("8".equals(gclb)){//建筑废弃物处置证延期
    				filePathName="/Templates/sjtzspfxn8.doc";
    				if("qusjtzs".equals(form.getFileCode())){
    					filePathName="/Templates/qusjtzspfxn8.doc";
    				}
    			}
    	 }	
    	}
    	
    	//***  zhuhx end  **/
    	//String filePathName = wfTemplatePrintRefService.getPrintTemplateRelativePath(form.getTemplateId(), form.getFileCode()) ;
        
    	if(filePathName == null){
        	filePathName = "/wf/bi/bus-template/blank-template/blank.doc";
        }
    	try {
        	File file = null;
        	log.info("生成打印模版文件路径----------->"+filePathName);
        	filePathName = ExtBaseAction.getApplication().getRealPath("/") + File.separator +  filePathName; 
        	
            file = new File(filePathName);
            
        	//重置response
            ExtBaseAction.getResponse().reset();
            ExtBaseAction.getResponse().setContentType("application/octet-stream");
            
            ExtBaseAction.getResponse().setHeader("Content-Disposition","attachment; filename=" + filePathName);

            in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
            out = ExtBaseAction.getResponse().getOutputStream();
            byte[] buffer = new byte[BUFFER_SIZE];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
            	out.write(buffer, 0, n);
            }
            
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
			try {
				if(in != null) {
					in.close();
				}
				if(out != null) {
					out.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
        
		return null;
	}
	
	/**
	 * 获取业务表字段列表
	 * @throws Exception
	 */
	public String getBusTableFields()throws Exception {
		//获取业务表
		List<SysMetaTableForm> tables = wfBusTemplateService.getRelateEntities(form.getTemplateId());
		List<ExtMetaTableNode> nodes = null;
		
		if(tables != null && tables.size() > 0){
			
			nodes = new ArrayList<ExtMetaTableNode>();
			//对于每一个表
			for(SysMetaTableForm metaTableForm:tables){
				
				ExtMetaTableNode node = SysMetaTableConvertor.convertToExtNode(metaTableForm);
				//获取表中的字段
				List<SysMetaColumnForm> columns = sysMetaColumnService.getColumnsByTableId(metaTableForm.getId());
				
				List<ExtMetaColumnNode> children = SysMetaColumnConvertor.convertToExtNodeList(columns);
				node.setChildren(children);
				if(children == null)
					node.setLeaf(true);
				nodes.add(node);
			}
		}
		
		extRenderListJson(nodes, false);
		return null;
	}
	
	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub
		if(id != null){
			form = (WfTemplateAttachmentRefFormEX)wfTemplatePrintRefServiceEX.get(id);
		}
		else
			form = new WfTemplateAttachmentRefFormEX();
	}

	public WfTemplateAttachmentRefForm getModel() {
		// TODO Auto-generated method stub
		return form;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getIds() {
		return ids;
	}

	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	public Attachment getDocument() {
		return document;
	}

	public void setDocument(Attachment document) {
		this.document = document;
	}

}
